# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QVBoxLayout, QFrame, QDialog, QMessageBox
from PyQt5.QtCore import Qt, QCoreApplication
import sys
from Window.TeacherUI import Ui_ServerMainWindow
from PyQt5.QtWidgets import QApplication,QTableWidgetItem,QMainWindow
from ScokerTool import server
import threading
import json
from functools import partial
import os


class Teacher(QMainWindow, Ui_ServerMainWindow):
    def __init__(self):
        super(Teacher, self).__init__()

        self.select_item = None
        self.setupUi(self)
        self.line_number = 0
        self.name = 0
        self.sc =  0

        self.start()
        self.clear_interface()
        self.interface()
        self.singner()
        self.show()

    def check_score(self):
        ##检查学生成绩
        try:
            with open('score',mode= 'r' ,encoding='utf-8') as rf:
                info = rf.readline()
            self.sc = json.loads(info)[0]
            self.name = json.loads(info)[1]
            user_list = []
            for user in self.user_message:
                user_list.append(user[1])
            col_number = user_list.index(self.name)
            self.tableWidget.setItem(int(col_number), 3, QTableWidgetItem(str(self.sc)))

        except:
            pass


    def start(self):
        # 开始多线程
        self.server_thread = threading.Thread(target=server.server_start)
        self.server_thread.setDaemon(True)
        self.server_thread.start()


    def singner(self):
        # 连接信号
        self.pushButton.clicked.connect((lambda: self.tabWidget.setCurrentIndex(0)))
        self.pushButton_2.clicked.connect((lambda: self.tabWidget.setCurrentIndex(1)))
        self.pushButton_3.clicked.connect((lambda: self.tabWidget.setCurrentIndex(2)))
        self.pushButton_4.clicked.connect(self.write_class)
        self.pushButton_5.clicked.connect(self.add_row)
        self.pushButton_6.clicked.connect(self.check_score)
        self.pushButton_7.clicked.connect(self.delete_class)
        #self.pushButton_7.clicked.connect(partial(self.say, self.select_item))
        #self.listWidget.

    def write_meth(self):
        print ('文件操作完成。')
        os.remove('./info')
        with open('info', 'w',encoding='utf-8') as wf:
            wf.write(json.dumps(self.user_message,ensure_ascii=False))
            wf.write('\n')
            wf.write(json.dumps(self.welcome_message,ensure_ascii=False))
            wf.write('\n')
            wf.write(json.dumps(self.class_message,ensure_ascii=False))
            wf.write('\n')

    def write_class(self):
        #课程写入
        self.class_message.append({"实验名":self.lineEdit_2.text(),"实验标题":self.lineEdit.text(),"实验内容":self.textEdit.toPlainText()})
        self.write_meth()
        self.interface()
    def delete_class(self,choose_number):
        # 课程删除
        try:
            self.class_message.remove(self.class_message[self.listWidget.row(self.select_item)])
            self.write_meth()
            self.interface()
        except:
            pass
    def clear_interface(self):
        # 清除设计时加上的文字
        self.listWidget.clear()

    def flash_face(self):
        self.clear_interface()
        with open('info', 'r', encoding='utf-8') as f:
            self.user_message = f.readline().strip('\n')
            self.welcome_message = f.readline().strip('\n')
            self.class_message = f.readline().strip('\n')
        self.user_message = json.loads(self.user_message)
        self.welcome_message = json.loads(self.welcome_message)
        self.class_message = json.loads(self.class_message)

        # 实验名称列表
        for i in self.class_message:
            self.listWidget.addItem(i['实验名'])

        # 设置欢迎信息
        self.textBrowser_2.setText(self.welcome_message['课程介绍'])
        # 设置选中显示
        self.listWidget.itemClicked.connect(self.show_class_message)

        # tabwidget设置
        self.line_number = len(self.user_message)
        self.tableWidget.setRowCount(self.line_number)
        for y in range(len(self.user_message[0])):
            for x in range(len(self.user_message)):
                self.tableWidget.setItem(x, y, QTableWidgetItem(self.user_message[x][y]))

    def interface(self):
        # 界面刷新，展示
        self.clear_interface()
        with open('info', 'r', encoding='utf-8') as f:
            self.user_message = f.readline().strip('\n')
            self.welcome_message = f.readline().strip('\n')
            self.class_message = f.readline().strip('\n')
        self.user_message = json.loads(self.user_message)
        self.welcome_message = json.loads(self.welcome_message)
        self.class_message = json.loads(self.class_message)

        #实验名称列表
        for i in self.class_message:
            self.listWidget.addItem(i['实验名'])

        # 设置欢迎信息
        self.textBrowser_2.setText(self.welcome_message['课程介绍'])
        # 设置选中显示
        self.listWidget.itemClicked.connect(self.show_class_message)


        # tabwidget设置
        self.line_number = len(self.user_message)
        self.tableWidget.setRowCount(self.line_number)
        for y in range(len(self.user_message[0])):
            for x in range(len(self.user_message)):
                self.tableWidget.setItem(x, y, QTableWidgetItem(self.user_message[x][y]))

    def add_row(self):
        #添加一行
        self.line_number += 1
        self.tableWidget.setRowCount(self.line_number)

    def show_class_message(self, item):
        #选中课程后，显示标题和内容
        self.select_item = item
        for i in range(len(self.class_message)):
            if self.class_message[i]['实验名'] == item.text():
                self.lineEdit_2.setText(self.class_message[i]['实验名'])
                self.lineEdit.setText(self.class_message[i]['实验标题'])
                self.textEdit.setText(self.class_message[i]['实验内容'])

    def show_class(self):
        # title
        self.label.setText('123')
        # content
        self.textBrowser.clear()
        self.textBrowser.append('内容')


class logindialog(QDialog):
    #登录界面
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('登录界面')
        self.resize(200, 200)
        self.setFixedSize(self.width(), self.height())
        self.setWindowFlags(Qt.WindowCloseButtonHint)

        ###### 设置界面控件
        self.frame = QFrame(self)
        self.verticalLayout = QVBoxLayout(self.frame)

        self.lineEdit_account = QLineEdit()
        self.lineEdit_account.setPlaceholderText("请输入账号")
        self.verticalLayout.addWidget(self.lineEdit_account)

        self.lineEdit_password = QLineEdit()
        self.lineEdit_password.setPlaceholderText("请输入密码")
        self.verticalLayout.addWidget(self.lineEdit_password)

        self.pushButton_enter = QPushButton()
        self.pushButton_enter.setText("确定")
        self.verticalLayout.addWidget(self.pushButton_enter)

        self.pushButton_quit = QPushButton()
        self.pushButton_quit.setText("取消")
        self.verticalLayout.addWidget(self.pushButton_quit)



        ###### 绑定按钮事件
        self.pushButton_enter.clicked.connect(self.on_pushButton_enter_clicked)
        self.pushButton_quit.clicked.connect(QCoreApplication.instance().quit)


    def on_pushButton_enter_clicked(self):
        # 点击登录
        if self.lineEdit_account.text() == "admin" and self.lineEdit_password.text() == "admin":
            # self.lineEdit_account.text() == "admin" and self.lineEdit_password.text() == "admin"
            # 通过验证，关闭对话框并返回1
            self.accept()

        else:
            QMessageBox.warning(self, '提示', "用户名或密码错误")
            return


if __name__ == "__main__":
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)


    app =  QApplication(sys.argv)
    login = logindialog()
    if login.exec_() == QDialog.Accepted:
        teachers = Teacher()
        sys.exit(app.exec_())

    sys.exit(app.exec_())